<?php
/**
 * 功能.用户Store Api
 * User: xwc
 * Date: 2023/10/23
 */

namespace App\Service\Core\User\User;

use App\Model\Core\User\UserModel;
use App\Service\Core\CoreBaseService;
use App\Service\ParamsService;
use App\Traits\ModelStoreTrait;

/**
 * @method $this setUsername($val) 姓名
 * @method $this setSex($val) 性别
 * @method $this setBirthday($val) 出生日期
 * @package App\Service\Core\User\User
 */
class UserStoreApiService extends CoreBaseService
{
    use ModelStoreTrait;

    /**
     * @param $user_id
     * @return array
     * @throws \Throwable
     */
    public function store($user_id): array
    {
        $user_id = (int)$user_id;
        $operate_by = $this->operate_by;
        if (empty($operate_by)) {
            return alert_info(1, '未设置操作人');
        }
        if ($user_id <= 0) {
            return alert_info(1, 'user_id参数错误');
        }
        $user_info = UserService::getInstance()->getOne($user_id);
        if (empty($user_info)) {
            return alert_info(1, '用户信息不存在');
        }
        if ($user_info['status'] != ParamsService::STATUS_ENABLE) {
            return alert_info(1, '用户已停用');
        }
        $data = [];
        $username = $this->getParam('username');
        if (empty($username)){
            return alert_info(1,'请填写姓名');
        }
        if (mb_strlen($username) < 1 && mb_strlen($username) > 10) {
            return alert_info(1, '姓名应该在1-10字符之间');
        }
        $data['username'] = $username;
        $sex = $this->getParam('sex');
        if (!array_key_exists($sex, ParamsService::$sex)){
            return alert_info(1,'请选择性别');
        }
        $data['sex'] = $sex;
        $birthday = $this->getParam('birthday');
        if (empty($birthday)){
            return alert_info(1,'请选择出生日期');
        }
        if (!strtotime($birthday)) {
            return alert_info(1, '出生日期应该为日期格式');
        }
        if (strtotime($birthday) > time()){
            return alert_info(1,'出生日期应该小于当前时间');
        }
        $birthday = date('Y-m-d', strtotime($birthday));
        $data['birthday'] = $birthday;
        if (empty($data)) {
            return alert_info(1, '修改内容为空');
        }
        $change_data = easy_check_change_data($user_info, $data);
        if (empty($change_data)) {
            return alert_info(0, '修改成功');
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['updated_by'] = $operate_by;
        $res = UserModel::getInstance()->updateOne($user_id, $data);
        if (!$res) {
            return alert_info(1, '修改信息失败');
        }
        $msg = "api修改用户【{$user_info['username']}】 user_id:{$user_id}";
        $this->addLog('用户管理', $msg, $user_id, $operate_by);
        return alert_info(0, '修改成功');
    }
}
